
package com.x52im.rbchat.logic.sns_friend;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.eva.android.widget.ChoiceItemPopWindow;
import com.eva.android.widget.DataLoadableActivity;
import com.eva.android.widget.WidgetUtils;
import com.eva.android.widget.WidgetUtils.ToastType;
import com.eva.android.widget.alert.AlertDialog;
import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.dto.DataFromServer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.x52im.rbchat.MyApplication;
import com.x52im.rbchat.R;
import com.x52im.rbchat.cache.FriendsListProvider;
import com.x52im.rbchat.cache.ImageCacheLoader;
import com.x52im.rainbowchat.http.logic.dto.RosterElementEntity;
import com.x52im.rainbowchat.http.logic.dto.TimeToolKit;
import com.x52im.rbchat.logic.chat_friend.FriendChattingActivity;
import com.x52im.rbchat.logic.more.avatar.AvatarHelper;
import com.x52im.rbchat.logic.profile.ProfileHelper;
import com.x52im.rbchat.logic.profile.photo.UploadPhotoHelper;
import com.x52im.rbchat.logic.sns_friend.impl.SendFriendReqUIWrapper;
import com.x52im.rbchat.network.http.HttpRestHelper;
import com.x52im.rbchat.network.http.async.DeleteFriendAsync;
import com.x52im.rbchat.utils.IntentFactory;
import com.x52im.rbchat.utils.ToolKits;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Vector;

/**
 * 用户/好友信息查看Activity.
 * 
 * @author Jack Jiang(http://www.52im.net/space-uid-1.html)
 * @since 1.0
 */
public class FriendInfoActivity extends DataLoadableActivity 
{
	private static String TAG = FriendInfoActivity.class.getSimpleName();

	/** 常量：进入好友备注编辑界面的请求码 */
	public final int REQUEST_CODE_FOR_GO_TO_REMARK_EDIT = 1;

	/** 标题栏上的"更多"按钮 */
	private Button btnMore = null;
	/** 标题栏上的"更多"按钮对应的弹出菜单 */
	private MorePopWindow menuWindow = null;

	/** 子布局：相册 */
	private ViewGroup layoutOfPhotos = null;
	/** 子布局：声音 */
	private ViewGroup layoutOfPVoices = null;
	/** 子布局 - 组件：相片数 */
	private TextView viewPhotosCount = null;
	/** 子布局 - 组件：声音数 */
	private TextView viewPVoicesCount = null;
	
	/** 标签组件：好友的昵称显示（优先显示备注） */
	private TextView viewNickname = null;
	/** 标签组件：好友的原始昵称显示 */
	private TextView viewOriginalNickname = null;
	/** 标签组件：好友的uid */
	private TextView viewUid = null;
	/** 标签组件：好友的注册时间 */
	private TextView viewRegisterTime = null;
	/** 标签组件：好友状态*/
	private TextView viewStatus = null;
	/** 标签组件：好友的最近登陆时间 */
	private TextView viewLatestLoginTime = null;
	/** 标签组件：陌生人标签 */
	private TextView viewGuestFlag = null;

	/** 签名 */
	private TextView viewWhatsup = null;
	/** 其它说明 */
	private TextView viewOtherCaption = null;
	/** 图片组件：头像 */
	private ImageView viewAvadar = null;
	
	/** 按钮：底部右按钮 */
	private Button btnBottomRight = null;
	/** 按钮：底部左按钮 */
	private Button btnBottomLeft = null;

	//------------------------------ 以下组件只在对方是好友时显示 START
	/** 子布局：好友备注 */
	private ViewGroup layoutRemark = null;
	/** 子布局：电话号码 */
	private ViewGroup layoutMobileNum = null;
	/** 子布局：更多描述 */
	private ViewGroup layoutMoreDesc = null;

	private View viewMobileNumHSeperator = null;
	private View viewMoreDescHSeperator = null;

	private Button btnRemark = null;
	private Button btnMobileNum = null;
	private Button btnMoreDesc = null;

	private TextView viewMobileNum = null;
	private TextView viewMoreDesc = null;
	//------------------------------ 以下组件只在对方是好友时显示 END

	
	// 本变量目前仅用于Activity被create时从Intent中取出来的聊天好友信息对象.
	/**
	 * 为何不直接在 initDataFromIntent()方法中调用switchToFriends(..)呢？
	 * 原因在于，根据Activoty的生命周期，该方法里需要用到ui组件（被onCreate()调用），
	 * 而在initDataFromIntent()方法中Activity的ui组件还没有初始化完毕，所以只能先
	 * 暂存，然后再在后绪方法中使用即可 */
	private RosterElementEntity friendInfoForInit = null;
	
	/**
	 * 解析从Intent中传过来的可能的数据本方法中实现.
	 * 例如从上一个activity中传过来的数据，本方法被 {@link #init(Bundle)}调用。
	 */
	@Override
	protected void initDataFromIntent()
	{
		//解析从intent中传过来的数据
		ArrayList intentDatas = IntentFactory.parseFriendInfoIntent(getIntent());
		friendInfoForInit = (RosterElementEntity)intentDatas.get(0);
	}

	/**
	 * 本方法由父类的onCreate()调用，子类可在此方法中实现自已的UI显示逻辑。
	 */
	@Override
	protected void initViews(Bundle savedInstanceState)
	{
		// 设定自定义标题栏（设定此值即意味着开启自定义标题栏的使用，必须要在setContentView前设定）
		customeTitleBarResId = R.id.sns_friend_info_form_titleBar;
		// 养成良好习惯：首先设置主layout，确保后绪的操作中使用到的组件都可以被find到
		setContentView(R.layout.sns_friend_info);
		
		// 初始化各种组件
		viewNickname = findViewById(R.id.sns_friend_info_form_nickNameView);
		viewOriginalNickname = findViewById(R.id.sns_friend_list_form_item_originalNickNameView);
		viewUid = findViewById(R.id.sns_friend_info_form_uidView);
		viewRegisterTime = findViewById(R.id.sns_friend_info_form_registerTimeView);
		viewLatestLoginTime = findViewById(R.id.sns_friend_info_form_latestLoginTimeView);
		viewGuestFlag = findViewById(R.id.sns_friend_info_form_guestFlagView);
		btnBottomRight = findViewById(R.id.sns_friend_info_form_addFriendBtn);
		btnBottomLeft = findViewById(R.id.sns_friend_info_form_temporay_chat_ex_btn);
		viewAvadar = findViewById(R.id.sns_friend_info_form_friendAdavarImageView);
		viewStatus = findViewById(R.id.sns_friend_list_form_item_status);
		viewWhatsup = findViewById(R.id.sns_friend_list_form_item_whatsupView);
		viewOtherCaption = findViewById(R.id.sns_friend_list_form_item_othercaptionView);
		
		layoutOfPhotos = findViewById(R.id.sns_friend_list_form_item_photos_LL);
		layoutOfPVoices = findViewById(R.id.sns_friend_list_form_item_profilevoices_LL);
		viewPhotosCount = findViewById(R.id.sns_friend_list_form_item_photos_count);
		viewPVoicesCount = findViewById(R.id.sns_friend_list_form_item_pvoices_count);

		layoutRemark = findViewById(R.id.sns_friend_list_form_layout_remark);
		layoutMobileNum = findViewById(R.id.sns_friend_list_form_item_mobileNumLayout);
		layoutMoreDesc = findViewById(R.id.sns_friend_list_form_item_moreDescLayout);
		viewMobileNumHSeperator = findViewById(R.id.sns_friend_list_form_item_mobileNumHSeperator);
		viewMoreDescHSeperator = findViewById(R.id.sns_friend_list_form_item_moreDescHSeperator);
		btnRemark = findViewById(R.id.sns_friend_list_form_item_setRemarkBtn);
		btnMobileNum = findViewById(R.id.sns_friend_list_form_item_mobileNumBtn);
		btnMoreDesc = findViewById(R.id.sns_friend_list_form_item_moreDescBtn);
		viewMobileNum = findViewById(R.id.sns_friend_list_form_item_mobileNum_text);;
		viewMoreDesc = findViewById(R.id.sns_friend_list_form_item_update_moreDesc_text);;
		
		// 根据Intent传过来的数据初始化UI组件
		// * 如果该人员已经是好友了，则隐藏“加好友”、“临时聊天”按钮
		if(isFriend()){
			// 文字显示为"视频聊天"
			btnBottomRight.setText($$(R.string.sns_friend_info_form_info_friend_video_chat));
			btnBottomRight.setTextColor(getResources().getColor(R.color.common_list_light_blue_for_text));
			WidgetUtils.setDrawLeft(this, R.drawable.sns_friend_info_form_video_ico, btnBottomRight);
			// 文字显示为"发送消息"
			btnBottomLeft.setText($$(R.string.sns_friend_info_form_info_friend_chat));
			// 隐藏陌生人标签
			viewGuestFlag.setVisibility(View.GONE);
			// 显示好友备注显示和编辑ui
			layoutRemark.setVisibility(View.VISIBLE);

			// 是好友的话，就显示标题栏的更多按钮及事件处理
			btnMore = this.getCustomeTitleBar().getRightGeneralButton(R.drawable.common_title_btn_more);
		}
		else{
			// 文字显示为"加为好友"
			btnBottomRight.setText($$(R.string.sns_friend_info_form_info_add_friend));
			WidgetUtils.setDrawLeft(this, R.drawable.sns_friend_info_form_add_ico, btnBottomRight);
			// 文字显示为"临时聊天"
			btnBottomLeft.setText($$(R.string.sns_friend_info_form_info_temporay_chat_ex));
			// 隐藏好友备注显示和编辑ui
			layoutRemark.setVisibility(View.GONE);
			// 如果是系统账号则显示为"管理员"字样，防止别人仿冒
			viewGuestFlag.setText(ToolKits.isSystemAdmin(friendInfoForInit.getUser_uid())?"管理员":$$(R.string.sns_friend_info_form_info_guest_flag));
		}

		// 设置标题
		this.setTitle(R.string.sns_friend_info_form_title);
		//
		this.setLoadDataOnCreate(false);
		// 根据Intent中传过来的U友信息数据，刷新UI界面显示
		this.refreshToView(friendInfoForInit);
		// 尝试读取用户的照片缩略图并于以显示
		new PreviewPhotosAsyncTask(this).execute();
	}

	/**
	 * 本方法由父类的onCreate()调用，子类可在此方法中为各UI功能组件增加事件临听。
	 */
	@Override
	protected void initListeners()
	{
		// 是好友的话，就显示标题栏的更多按钮及事件处理
		if (isFriend()) {
			// "更多"菜单项点击事件处理
			btnMore.setOnClickListener(v -> showMenuWindow());
		}

		// 添加好友
		btnBottomRight.setOnClickListener(v -> {
			if (!checkValidForTempChat(true, false))
				return;

			// 对方是好友时，该按钮的功能是"视频聊天"
			if (isFriend()) {
				FriendChattingActivity.gotoRealtimeVideoChatCall(this, friendInfoForInit.getUser_uid(), friendInfoForInit.getNickname());
			}
			// 对方是陌生人时，该按钮的功能是"加为好友"
			else {
				// 最多好同时拥有的好友数
				RosterElementEntity local = imc().getLocalUserInfo();
				int maxFriend = CommonUtils.getIntValue(local == null ? "1" : local.getMaxFriend());
				SendFriendReqUIWrapper.sendAddFriendRequestWidthDialog(FriendInfoActivity.this
						, friendInfoForInit.getUser_uid()
						, friendInfoForInit.getNickname()
						, maxFriend);
			}
		});

		// 点击进入聊天界面
		btnBottomLeft.setOnClickListener(v -> {
			if (!checkValidForTempChat(true, false))
				return;

			// 如果已经是好友了，则点击直接进入正式聊天，否则进入临时聊天
			if (isFriend()) {
				startActivity(IntentFactory.createChatIntent(self(), friendInfoForInit.getUser_uid()));
			} else {
				startActivity(IntentFactory.createTempChatIntent(self(), friendInfoForInit.getUser_uid(), friendInfoForInit.getNickname()));
			}
		});

		// 点击头像看大图
		findViewById(R.id.sns_friend_info_form_friendAdavarImageView).setOnClickListener(v -> {
			if (ToolKits.isSystemAdmin(friendInfoForInit.getUser_uid())) {
				WidgetUtils.showToastLong(self(), "系统账号，没有头像可看哦！", ToastType.WARN);
				return;
			}

			// 头像文件名为空即表示没有设置过头像
			if (!CommonUtils.isStringEmpty(friendInfoForInit.getUserAvatarFileName())) {
				AvatarHelper.showAvatarImage(self(), friendInfoForInit.getUser_uid(), null);
			} else {
				WidgetUtils.showToastLong(self(), $$(R.string.user_info_avatar_image_not_exists), ToastType.WARN);
			}
		});

		// 点击查看相册
		layoutOfPhotos.setOnClickListener(v -> {
			if (friendInfoForInit != null)
				startActivity(IntentFactory.createPhotosViewActivityIntent(self(), friendInfoForInit.getUser_uid(), false));
		});
		// 点击查看个人语音介绍
		layoutOfPVoices.setOnClickListener(v -> {
			if (friendInfoForInit != null)
				startActivity(IntentFactory.createPVoiceViewActivityIntent(self(), friendInfoForInit.getUser_uid(), false));
		});

		// 只要好友才显示好友备注相关的编辑和显示功能
		if (isFriend()) {
			OnClickListener toRemarkEditFormLis = v ->
					startActivityForResult(IntentFactory.createFriendRemarkEditIntent(self(), friendInfoForInit.getUser_uid()), REQUEST_CODE_FOR_GO_TO_REMARK_EDIT);

			btnRemark.setOnClickListener(toRemarkEditFormLis);
			btnMobileNum.setOnClickListener(toRemarkEditFormLis);
			btnMoreDesc.setOnClickListener(toRemarkEditFormLis);
		}
	}
	
	/**
	 * 临时聊天对象合法性检查.
	 * 
	 * @return
	 */
	private boolean checkValidForTempChat(boolean checkIfMeself, boolean checkIsFriend)
	{
		// 自已不能发送消息给自已
		if(checkIfMeself && friendInfoForInit.getUser_uid().equals(lu() != null?lu().getUser_uid():null))
		{
			WidgetUtils.showToastLong(self(), $$(R.string.sns_friend_info_form_tempchat_self_tip), ToastType.WARN);
			return false;
		}
		
		// 检查当前要添加的好友是否已经存在于列表中（存在当然就不能重复加好友了）
		// * 注：其实最严谨的方法是服务端判断（实时根据数据结果查询），但通过网络
		// * 与服务端交互因网速原因会影响体验，所以先行在客户端做一个理论上不太严
		// * 谨的判断，先行处理掉可能的重复也是合情合理的
		if(checkIsFriend && isFriend())
		{
			WidgetUtils.showToastLong(self(), com.eva.android.ToolKits.i18n(this, R.string.sns_friend_info_form_tempchat_hasadd_tip, friendInfoForInit.getNickname()), ToastType.WARN);
			return false;
		}
		
		return true;
	}

	/**
	 * 当前用户是否是好友（在好友列表中就认为是好友）。
	 *
	 * @return true表示是，否则不是
	 */
	private boolean isFriend() {
		FriendsListProvider flp = imc().getFriendsListProvider();
		return (friendInfoForInit != null &&  flp != null && flp.isUserInRoster2(friendInfoForInit.getUser_uid()));
	}
	
	/**
	 * 从服务端查询数据并返回.
	 * 本类中无需单独查询数据（直接通过Intent传进来的）。
	 * 
	 * @param params loadData中传进来的参数，本类中该参数没有被用到
	 */
	@Override 
	protected DataFromServer queryData(String... params)
	{
		return null;
	}

	//将已构造完成的完整的明细数据放入列表中显示出来
	@Override 
	protected void refreshToView(Object dateToView)
	{
		if(dateToView != null && dateToView instanceof RosterElementEntity)
		{
			RosterElementEntity friendInfo = (RosterElementEntity)dateToView;
			
			viewNickname.setText(friendInfo.getNickNameWithRemark());
			viewOriginalNickname.setText("昵称："+friendInfo.getNickname());
			viewUid.setText(friendInfo.getUser_uid());
			viewRegisterTime.setText(friendInfo.getRegister_time());
			viewLatestLoginTime.setText(CommonUtils.isStringEmpty(friendInfo.getLatest_login_time())?"从未登陆": getLatestLoginTimeStr(friendInfo.getLatest_login_time()));
			viewStatus.setText(friendInfo.isOnline() ? $$(R.string.sns_friend_list_form_item_status_online) : $$(R.string.sns_friend_list_form_item_status_offline));
			viewStatus.setTextColor(friendInfo.isOnline() ? getResources().getColor(R.color.sns_friend_list_form_item_status_txt_color_online) :getResources().getColor(R.color.sns_friend_list_form_item_status_txt_color_offline));
			
			// 设置个人签名
			if(!CommonUtils.isStringEmpty((String)friendInfo.getWhatsUp(), true))
				viewWhatsup.setText((String)friendInfo.getWhatsUp());
			
			// 设置其它说明
			if(!CommonUtils.isStringEmpty((String)friendInfo.getUserDesc(), true))
				viewOtherCaption.setText((String)friendInfo.getUserDesc());
			else
				viewOtherCaption.setText("-");
			
			// 设置性别图标
			Drawable sexImg;
			int resId = friendInfo.isMan() ? R.drawable.sns_friend_list_form_item_male_img : R.drawable.sns_friend_list_form_item_female_img;
			sexImg = getResources().getDrawable(resId);
			sexImg.setBounds(0, 0, sexImg.getMinimumWidth(), sexImg.getMinimumHeight());
			viewStatus.setCompoundDrawables(null, null, sexImg, null);

			// 头像文件名为空即表示没有设置过头像
			if(!CommonUtils.isStringEmpty(friendInfoForInit.getUserAvatarFileName())) {
				// 显示用户头像（强制从网络加载用户头像，目的是确保在用户主动查看的情况下能尽最大可能读取该用户的最新头像，其它关联的缓存也就能随之刷新显示了）
				ImageCacheLoader.loadAvatarImgWithGlide(this, friendInfoForInit.getUser_uid(), friendInfoForInit.getUserAvatarFileName()
						, viewAvadar, 35, R.drawable.default_avatar_yuan_70_3x, true, true);
			}

			// 关于好友备注的ui显示内容和逻辑
			refreshToViewForRemark(friendInfo);
		}
		else
		{
			Log.w(TAG, "dateToView="+dateToView);
			WidgetUtils.showToast(FriendInfoActivity.this, "dateToView="+dateToView, ToastType.WARN);
		}
		
		//## Bug FIX START：by JackJiang
		if(friendInfoForInit == null)
		{
			new AlertDialog.Builder(FriendInfoActivity.this)
			.setTitle("提示")
			.setMessage("APP出现了未知异常，请退出后再重新启动应用！")
			.setPositiveButton($$(R.string.general_ok), null) 
			.show(); 

			return;
		}
		//## Bug FIX END
		
		// 获取该用户的相片数、声音数
		new ProfileHelper.QueryPhotosAndPVoiceCountAsyncTask(this, friendInfoForInit.getUser_uid()){
			/**
			 * 成功处理后要调用的方法：找到了相片数.
			 */
			@Override
			protected void onPostExecute_findPhotoCount(int count) {
				if (count > 0) {
					layoutOfPhotos.setVisibility(View.VISIBLE);
					viewPhotosCount.setVisibility(View.VISIBLE);
					viewPhotosCount.setText(String.valueOf(count));
				} else {
//					layoutOfPhotos.setVisibility(View.GONE);
					viewPhotosCount.setVisibility(View.GONE);
				}
			}

			/**
			 * 成功处理后要调用的方法：找到了我的声音数.
			 */
			@Override
			protected void onPostExecute_findPVoiceCount(int count) {
				if (count > 0) {
					layoutOfPVoices.setVisibility(View.VISIBLE);
					viewPVoicesCount.setVisibility(View.VISIBLE);
					viewPVoicesCount.setText(String.valueOf(count));
				} else {
//					layoutOfPVoices.setVisibility(View.GONE);
					viewPVoicesCount.setVisibility(View.GONE);
				}
			}
		}
		.execute();
	}

	/**
	 * 刷新关于好友备注的ui显示内容和逻辑.
	 *
	 * @param friendInfo
	 */
	private void refreshToViewForRemark(RosterElementEntity friendInfo)
	{
		viewNickname.setText(friendInfo.getNickNameWithRemark());
		if (isFriend()) {
			boolean hasRemak = !CommonUtils.isStringEmpty(friendInfo.getFriendRemark());
			if (hasRemak)
				this.viewOriginalNickname.setVisibility(View.VISIBLE);
			else
				this.viewOriginalNickname.setVisibility(View.GONE);

			this.viewMobileNum.setText(friendInfo.getFriendMobileNum());
			this.viewMoreDesc.setText(friendInfo.getFriendMoreDesc());

			if (!CommonUtils.isStringEmpty(friendInfo.getFriendMobileNum(), true)) {
				this.layoutMobileNum.setVisibility(View.VISIBLE);
				this.viewMobileNumHSeperator.setVisibility(View.VISIBLE);
			} else {
				this.layoutMobileNum.setVisibility(View.GONE);
				this.viewMobileNumHSeperator.setVisibility(View.GONE);
			}
			if (!CommonUtils.isStringEmpty(friendInfo.getFriendMoreDesc(), true)) {
				this.layoutMoreDesc.setVisibility(View.VISIBLE);
				this.viewMoreDescHSeperator.setVisibility(View.VISIBLE);
			} else {
				this.layoutMoreDesc.setVisibility(View.GONE);
				this.viewMoreDescHSeperator.setVisibility(View.GONE);
			}
		}
	}

	/**
	 * 显示界面底部的弹出菜单。
	 */
	public void showMenuWindow() {
		//为弹出窗口实现监听类
		final View.OnClickListener itemsOnClick = v -> {
			menuWindow.dismiss();
			// 从相册中选择
			if (v.getId() == R.id.sns_friend_info_popmenu_dialog_btn_delete) {
				new AlertDialog.Builder(self())
						.setTitle(R.string.roster_list_delete_title)
						.setMessage(MessageFormat.format($$(R.string.roster_list_delete_confirm_message), friendInfoForInit.getNickNameWithRemark()))
						.setPositiveButton(R.string.general_yes, (dialog, which) -> new DeleteFriendAsync(self()).execute(friendInfoForInit))
						.setNegativeButton(R.string.general_no, null)
						.show();
			}
		};

		// 实例化SelectPicPopupWindow
		menuWindow = new MorePopWindow(this, itemsOnClick);
		// 显示窗口
		menuWindow.showAtLocation(findViewById(R.id.sns_friend_info_MainLL), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
	}

	/**
	 * 从下一个Activity回来后的数据回调。
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(resultCode != Activity.RESULT_OK) {
			//result is not correct
			return;
		}

		// 表示这是从好友备注编辑界面返回的，那么就尝试刷新备注相关的信息显示吧（因为在这个界面里可能已经修改了这些内容哦）
		if(requestCode == REQUEST_CODE_FOR_GO_TO_REMARK_EDIT) {
			if(friendInfoForInit != null){
				// friendInfoForInit 这个对象是通过Intent传过来的，因而它是反序化后的对象克隆，紧随新对象应从好友列表中实时取出才是哦
				RosterElementEntity latestRee = imc().getFriendsListProvider().getFriendInfoByUid2(friendInfoForInit.getUser_uid());
				if(latestRee != null){
					refreshToViewForRemark(latestRee);
				}
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	
	//================================================================================= 内部类

	/**
	 * 标题栏"更多"按钮对应的弹出窗口式菜单实现类。
	 */
	private class MorePopWindow extends ChoiceItemPopWindow {
		private Button btnDelete, btnCancel;

		public MorePopWindow(Activity context, View.OnClickListener mItemsOnClick) {
			super(context, mItemsOnClick, R.layout.sns_friend_info_popmenu_dialog, R.id.sns_friend_info_popmenu_dialog_pop_layout);
		}

		protected void initContentViewComponents(View mMenuView) {
			btnDelete = mMenuView.findViewById(R.id.sns_friend_info_popmenu_dialog_btn_delete);
			btnCancel = mMenuView.findViewById(R.id.sns_friend_info_popmenu_dialog_btn_cancel);
			// 取消按钮
			btnCancel.setOnClickListener(createCancelClickListener());
			// 设置按钮监听
			btnDelete.setOnClickListener(mItemsOnClick);
		}
	}

	/**
	 * 该用户的照片缩略图读取及预览异步实现类。
	 */
	public class PreviewPhotosAsyncTask extends AsyncTask<Object, Integer, DataFromServer>
	{
		private Context parentActivity = null;

		public PreviewPhotosAsyncTask(Context parentActivity)
		{
			this.parentActivity = parentActivity;
		}

		/**
		 * 在后台执行 .
		 * 
		 * @param params 外界传进来的参数
		 * @return 查询结果，将传递给onPostExecute(..)方法
		 */
		@Override
		protected DataFromServer doInBackground(Object... params) 
		{
			// 当前服务端默认取最新的4 张照片
			return HttpRestHelper.queryPhotosPreviewListFromServer(friendInfoForInit.getUser_uid());
		}

		/**
		 * 处理服务端返回的结果信息.
		 */
		protected void onPostExecute(DataFromServer result)
		{
			if(result != null && result.isSuccess())
			{
				try {
					Vector<Vector> rets = new Gson().fromJson((String)result.getReturnValue(), new TypeToken<Vector<Vector>>(){}.getType());
					if(rets.size() > 0) {
						ViewGroup previewLayout = findViewById(R.id.sns_friend_list_form_item_photos_previewLL);
						ImageView[] views = new ImageView[]{
								findViewById(R.id.sns_friend_list_form_item_photos_preview1View)
								, findViewById(R.id.sns_friend_list_form_item_photos_preview2View)
								, findViewById(R.id.sns_friend_list_form_item_photos_preview3View)
								, findViewById(R.id.sns_friend_list_form_item_photos_preview4View)
						};
						previewLayout.setVisibility(View.VISIBLE);

						int i = 0;
						for(Vector row : rets) {
							String res_file_name = (String)row.get(0);

							ImageView view = views[i++];
							view.setVisibility(View.VISIBLE);

							// ********** 设置缩略图显示
							ImageCacheLoader.loadImgWithGlide(parentActivity
									// 从网络读取（图片的缩略图，服务端存放的缩略图是原图文件名前带“th_”有前缀即查）
									, UploadPhotoHelper.getPhotoDownloadURL(parentActivity, "th_"+res_file_name)
									, null, view, 10 // 6
									, R.drawable.common_default_img_no_border_50dp_3x_r30px
									, -1, false, false);
						}
					}
				}
				catch (Exception e) {
					Log.w(PreviewPhotosAsyncTask.class.getSimpleName(), e.getMessage(), e);
				}
			}
		}
	}


	//================================================================================= 实用方法

	private static String getLatestLoginTimeStr(String timestampWithGMT)
	{
		return TimeToolKit.convertTimstampToDefaultTimeZone(timestampWithGMT, "yyyy-MM-dd HH:mm");
	}
}
